package dao.file;

import component.NodePersistenceComponent;
import dao.IMibModuleDao;
import dao.IMibNodeDao;
import model.MibModule;
import model.MibNode;
import util.common.DirectoryUtils;
import util.common.FileUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

public class MibFileDao implements IMibNodeDao, IMibModuleDao {
    private String baseDirectory;

//    public MibFileDao() {
//        this("Z:\\MibCache\\MibFile\\");
//    }

    public MibFileDao(String baseDirectory) {
        this.baseDirectory = baseDirectory;
        DirectoryUtils.createDirectory(baseDirectory);
    }

    public void save(String moduleName, Collection<MibNode> nodes){
        if (nodes == null)
            throw new IllegalArgumentException();
        List<String> lines = new ArrayList<>();
        for (MibNode node : nodes){
            lines.add(NodePersistenceComponent.toJson(node));
        }
        FileUtils.writeAllLines(getPath(moduleName), lines);
    }

    public void save(MibModule module){
        if (module == null)
            throw new IllegalArgumentException();
        if (module.moduleName == null)
            throw new IllegalArgumentException();
        this.save(module.moduleName, module.nodes.values());
    }

    @Override
    public List<MibNode> getByModuleName(String moduleName) {
        List<String> lines = FileUtils.readAllLines(getPath(moduleName));
        List<MibNode> nodes = new LinkedList<>();
        for (String line: lines){
            try {
                nodes.add(NodePersistenceComponent.fromJson(line));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return nodes;
    }

    private String getPath(String moduleName){
        return baseDirectory + "\\" + moduleName;
    }

    @Override
    public boolean isModuleExist(String moduleName) {
        if (moduleName == null)
            throw new IllegalArgumentException();
        String[] files = DirectoryUtils.getFiles(baseDirectory, (dir, name) -> name.equals(moduleName));
        return files.length > 0 ;
    }
}
